package com.koron.system.unityUser.service;

import cn.hutool.core.collection.CollectionUtil;
import com.koron.bean.system.org.OrgBean;
import com.koron.bean.system.staff.StaffBean;
import com.koron.common.core.util.CodeTools;
import com.koron.common.core.util.HanyupinyinUtil;
import com.koron.common.core.util.StringUtils;
import com.koron.system.unityUser.entity.*;
import com.koron.system.unityUser.feign.UnityFeignService;
import com.koron.system.unityUser.mapper.UnityUserMapper;
import com.koron.system.userOrg.bean.po.AppUserOrgPo;
import lombok.NonNull;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * description: UnityUserService
 * @author huangsj
 * @date 2023/6/29 15:56
 */
@Service
public class UnityUserService {

    @Autowired
    private UnityFeignService unityFeignService;

    @Autowired
    private UnityUserMapper unityUserMapper;
    /**
     * WS用户登录
     * @param permissionCode
     * @param userNameMd5
     * @param passwordMd5
     * @return
     */
    public WsResult<String> hello(String permissionCode,@NonNull String userNameMd5,@NonNull String passwordMd5) {
        return unityFeignService.hello(permissionCode,userNameMd5,passwordMd5);
    }

    /**
     * 标段类型字典
     * @param auth
     * @return
     */
    public WsResultList<UumsBidType> bidTypeDictionary(String auth) {
        return unityFeignService.bidTypeDictionary(auth);
    }

    /**
     * 机构类型字典
     * @param auth
     * @return
     */
    public WsResultList<UumsOrganizationType> organizationTypeDictionary(@NonNull String auth) {
        return unityFeignService.organizationTypeDictionary(auth);
    }

    /**
     * 系统状态字典
     * @param auth
     * @return
     */
    public WsResultList<UumsAppState> appStateDictionary(@NonNull String auth) {
        return unityFeignService.appStateDictionary(auth);
    }

    /**
     * 珠三角工程信息
     * @param auth
     * @return
     */
    public WsResult<UumsProject> project(@NonNull String auth) {
        return unityFeignService.project(auth);
    }

    /**
     * 组织机构信息
     * @param auth
     * @param organizationCode
     * @return
     */
    @Transactional
    public WsResultList<UumsOrganization> organizationList(@NonNull String auth, String organizationCode) {
        WsResultList<UumsOrganization> resultList = unityFeignService.organizationList(auth, organizationCode);
        if (resultList == null){
            return null;
        }
        List<OrgBean> orgBeans = new ArrayList<>();
        List<UumsOrganization> data = resultList.getData();
        if (CollectionUtils.isNotEmpty(data)){
            //拼装bean
            for (UumsOrganization org :
                    data) {
                OrgBean orgBean = new OrgBean();
                orgBean.setId(org.getOrganizationCode());
                orgBean.setName(org.getOrganizationName());
                String namePY = HanyupinyinUtil.getPinyinString(org.getOrganizationName());
                orgBean.setNamePy(namePY);
                orgBean.setAppid("8e7e09b125ea4dbc8d0515564ceda011d");
                orgBean.setParent(org.getParentCode());
                orgBean.setOutOrg("0"); // 默认为内单位
                int level = 1;
                for (int i = 0; i < org.getOrganizationCodePath().length(); i++) {
                    if (org.getOrganizationCodePath().charAt(i) == '>') {
                        //层级加一
                        level++;
                    }
                }
                // 兼容现有系统组织层级 1-公司、2-部门、3-单位
                if (level == 2 || level == 3){
                    level = 2;
                }
                if (level > 3){
                    level = level-1;
                }
                orgBean.setLevel(level+"");
                //拼装路径
                orgBean.setLevelPathName(org.getOrganizationNamePath());
                if(StringUtils.isNotEmpty(org.getOrganizationCodePath())) {
                    orgBean.setLevelPath(org.getOrganizationCodePath().replaceAll("-->","/"));
                    orgBean.setLevelPathName(org.getOrganizationNamePath().replaceAll("-->","/"));
//                    orgBean.setLevelPath(deleteCharString(org.getOrganizationCodePath(),'>','-'));
//                    orgBean.setLevelPathName(deleteCharString(org.getOrganizationNamePath(),'>','-'));
                }else {
                    orgBean.setLevelPath("/");
                    orgBean.setLevelPathName("/");
                }
                orgBean.setType(org.getOrganizationTypeName());
                String prefix = HanyupinyinUtil.getFirstLettersUpper(org.getOrganizationName());
                orgBean.setPrefix(prefix);
                orgBean.setSort(Integer.valueOf(org.getOrganizationOrder()));
                orgBean.setDeleteFlag(0);
                orgBeans.add(orgBean);
                orgBean.setCreateTime(new Date());
            }
            unityUserMapper.batchInsertOrg(orgBeans);
        }
        return resultList;
    }

//    public String deleteCharString(String sourceString, char chElemData,char chElemData2) {
//        StringBuilder stringBuilder = new StringBuilder("");
//        for (int i = 0; i < sourceString.length(); i++) {
//            if (sourceString.charAt(i) == chElemData) {
//                stringBuilder.append('/');
//                continue;
//            }
//            if (sourceString.charAt(i) != chElemData2) {
//                stringBuilder.append(sourceString.charAt(i));
//            }
//        }
//        return sourceString.toString();
//    }

    /**
     * 公司信息
     * @param auth
     * @param companyCode
     * @return
     */
    public WsResultList<UumsCompany> companyListcompanyList(String auth, String companyCode) {
        return unityFeignService.companyListcompanyList(auth,companyCode);
    }

    /**
     * 标段信息
     * @param auth
     * @param bidCode
     * @return
     */
    public WsResultList<UumsBid> bidListbidList(String auth, String bidCode) {
        return unityFeignService.bidListbidList(auth,bidCode);
    }

    /**
     * 子系统信息
     * @param auth
     * @param sysCode
     * @return
     */
    public WsResultList<UumsApp> appList(String auth, String sysCode) {
        return unityFeignService.appList(auth,sysCode);
    }

    /**
     * 通过ID查询用户授权信息
     * @param auth
     * @param uumsUserId
     * @return
     */
    public WsResultList<UumsApp> appListByUserId(String auth, String uumsUserId) {
        return unityFeignService.appListByUserId(auth,uumsUserId);
    }

    /**
     * 通过ID查询用户信息
     * @param auth
     * @param uumsUserId
     * @return
     */
    public WsResult<UumsUser> UserById(String auth, String uumsUserId) {
        WsResult<UumsUser> result = unityFeignService.UserById(auth, uumsUserId);
//        if (result == null ){
//            return null;
//        }
//        StaffBean staffBean = new StaffBean();
//        UumsUser uumsUser = result.getData();
//        staffBean.setId(uumsUser.getUserId());
//        staffBean.setName(uumsUser.getUserName());
//        staffBean.setNamePy(HanyupinyinUtil.getPinyinString(uumsUser.getUserName()));
//        staffBean.setAccount(uumsUser.getLoginName());
//        staffBean.setPhone(uumsUser.getPhone());
//        staffBean.setEmail(uumsUser.getEmail());
//        staffBean.setDeleteFlag(0);
//        unityUserMapper.insertUser(staffBean);
        return result;
    }

    /**
     * 通过用户名密码查询用户信息
     * @param auth
     * @param userNameMd5
     * @param passwordMd5
     * @return
     */
    public WsResultUumsUser UserByLNmPw(String auth, String userNameMd5, String passwordMd5) {
        return unityFeignService.UserByLNmPw(auth,userNameMd5,passwordMd5);
    }

    /**
     * 通过公司编码、组织机构编码、系统编码查询用户信息
     * @param auth
     * @param companyCode
     * @param organizationCode
     * @param sysCode
     * @return
     */
    @Transactional
    public WsResultList<UumsUser> UserList(String auth, String companyCode, String organizationCode, String sysCode) {
        WsResultList<UumsUser> resultList = unityFeignService.UserList(auth, companyCode, organizationCode, sysCode);
        if (resultList == null) {
            return null;
        }
        List<UumsUser> data = resultList.getData();
        List<StaffBean> staffBeans = new ArrayList<>();
        List<AppUserOrgPo> userOrgPos = new ArrayList<>();
        // 默认组织
        List<AppUserOrgPo> defaultUserOrgPos = new ArrayList<>();
        int j = 0;
        if (CollectionUtils.isNotEmpty(data)) {

            defaultUserOrgPos = unityUserMapper.findDefaultOrg();

            // 清空用户组织表，需求：确保用户管理的组织信息都是同步过来的
            unityUserMapper.truncateTable();

            for (int i = 0; i < data.size(); i++) {

                j += 1;
               //用户组织关系
                String loginName = data.get(i).getLoginName();
                List<UumsOrganization> uumsOrganizationList = data.get(i).getUumsOrganizationList();
                if (CollectionUtil.isNotEmpty(uumsOrganizationList)){
                    for (UumsOrganization uumsOrganization : uumsOrganizationList) {
                        AppUserOrgPo appUserOrgPo = new AppUserOrgPo();
                        appUserOrgPo.setAccount(loginName);
                        appUserOrgPo.setOrgId(uumsOrganization.getOrganizationCode());
                        appUserOrgPo.setUpdateTime(new Date());
                        appUserOrgPo.setDeleteFlag(0);
                        appUserOrgPo.setId(CodeTools.getCode32());
                        userOrgPos.add(appUserOrgPo);
                    }
                }

                //用户
                StaffBean staffBean = new StaffBean();
                // 把用户id和account改成一样的（兼容前端选人组件）
                staffBean.setId(data.get(i).getLoginName());
                staffBean.setName(data.get(i).getUserName());
                staffBean.setNamePy(HanyupinyinUtil.getPinyinString(data.get(i).getUserName()));
                staffBean.setAccount(data.get(i).getLoginName());
                staffBean.setPhone(data.get(i).getPhone());
                staffBean.setEmail(data.get(i).getEmail());
                staffBean.setUpdateTime(new Date());
                // 如果是禁用用户
                if ("0".equals(data.get(i).getInuse())){
                    // 系统内设置为已删除
                    staffBean.setDeleteFlag(1);

                }


                staffBeans.add(staffBean);
                if (j >= 100) {
                    unityUserMapper.batchInsertUser(staffBeans);
                    unityUserMapper.batchInUpUserOrg(userOrgPos);
                    j = 0;
                    staffBeans.clear();
                    userOrgPos.clear();
                }
            }
            unityUserMapper.batchInsertUser(staffBeans);
            unityUserMapper.batchInUpUserOrg(userOrgPos);
        }

        if (CollectionUtils.isNotEmpty(defaultUserOrgPos)){
            unityUserMapper.batchUpdate(defaultUserOrgPos);
        }

        return resultList;
    }

    /**
     * 修改用户密码
     * @param auth
     * @param userId
     * @param oldPasswordMd5
     * @param newPasswordMd5
     * @param confirmPasswordMd5
     * @return
     */
    public WsResult<Integer> changePassword(String auth, String userId, String oldPasswordMd5, String newPasswordMd5, String confirmPasswordMd5) {
        return unityFeignService.changePassword(auth,userId,oldPasswordMd5,newPasswordMd5,confirmPasswordMd5);
    }
}
